import { component$, Slot } from '@builder.io/qwik';
import { type RequestHandler, useLocation, useNavigate } from '@builder.io/qwik-city';
import { cond, T, always } from 'rambda';
import Tabs from '~/components/ui/Tabs';
import { shouldAuth } from '~/server/authn';
import { noCache } from '~/server/cache-control';

export const onRequest: RequestHandler = async (ev) => {
  await shouldAuth(ev);
  await ev.next();
};

export const onGet: RequestHandler = async (ev) => {
  noCache(ev);
};

export default component$(() => {
  const location = useLocation();
  const navigate = useNavigate();

  const toActiveTabKey: (path: string) => string = cond([
    [(it) => it === '/me/', always('/')],
    [(it) => it.startsWith('/me/post-collections'), always('/post-collections')],
    [T, always('/')],
  ]);

  return (
    <>
      <Tabs
        tabs={[
          { key: '/', title: '基本信息' },
          { key: '/post-collections', title: '我的文章' },
        ]}
        activeTabKey={toActiveTabKey(location.url.pathname)}
        onChange$={(key) => {
          navigate(`/me/${key}`);
        }}
      />
      <div>
        <Slot />
      </div>
    </>
  );
});
